<template>
    <div class="student-home">
        <header class="header-bar">
            <el-input v-model="search" placeholder="输入期刊名称" clearable class="search-input" prefix-icon="el-icon-search"
                @keyup.enter.native="searchJournals" />
            <el-button type="primary" @click="searchJournals" class="search-button">
                搜索
            </el-button>
        </header>

        <div class="main-content">
            <aside class="sidebar">
                <div class="sidebar-menu">
                    <el-button v-for="location in [{ location_id: '全部', location_name: '全部' }, ...libraryLocations]"
                        :key="location.location_id"
                        :class="['menu-item', { active: locationFilter === location.location_id }]"
                        @click="filterByLocation(location.location_id)" size="large">
                        {{ location.location_name }}
                    </el-button>
                </div>
            </aside>
            <section class="results-section">
                <div class="journal-list">
                    <div v-for="(journal, index) in journals" :key="index" class="journal-item">
                        <img :src="journal.image_url || 'default-cover.jpg'" alt="期刊封面" class="journal-cover" />

                        <div class="journal-content">
                            <div class="journal-info">
                                <p class="journal-title">{{ journal.journal_name || '未知期刊名称' }}</p>
                                <p><strong>馆藏地:</strong> {{ journal.location_name || '未知' }}</p>
                                <p><strong>地址:</strong> {{ journal.address || '暂无地址' }}</p>
                                <p><strong>出版信息:</strong> {{ journal.year || '暂无' }} 年, 卷 {{ journal.volume || '暂无' }},
                                    期 {{ journal.issue || '暂无' }}</p>
                                <p><strong>库存:</strong> <span
                                        :class="journal.stock > 0 ? 'in-stock' : 'out-of-stock'">{{ journal.stock > 0 ? journal.stock : '无库存' }}</span>
                                </p>
                                <p><strong>CN 编号:</strong> {{ journal.cn_number || '暂无' }}</p>
                                <p><strong>ISSN 编号:</strong> {{ journal.issn || '暂无' }}</p>
                                <p><strong>邮发代号:</strong> {{ journal.postal_code || '暂无' }}</p>
                                <p><strong>出版周期:</strong> {{ journal.publication_cycle || '暂无' }}</p>
                                <p><strong>出版地:</strong> {{ journal.publication_place || '暂无' }}</p>
                                <p><strong>主办单位:</strong> {{ journal.sponsor || '暂无' }}</p>
                            </div>
                            <div class="journal-actions">
                                <el-button type="success" size="small" :disabled="journal.stock <= 0"
                                    @click="openBorrowDialog(journal)">
                                    借阅
                                </el-button>
                                <el-button type="warning" size="small" :disabled="journal.stock <= 0"
                                    @click="openEntrustmentDialog(journal)">
                                    委托借阅
                                </el-button>
                            </div>
                        </div>
                    </div>
                </div>

                <el-pagination background layout="prev, pager, next" :total="totalCount" :page-size="pageSize"
                    v-model:current-page="currentPage" @current-change="fetchJournals" class="pagination" />
            </section>
        </div>

        <el-dialog title="借阅期刊" v-model="borrowDialogVisible" width="30%">
            <div>
                <p>期刊名称: {{ selectedJournal.journal_name }}</p>
                <el-date-picker v-model="borrowDate" type="date" placeholder="选择借阅日期" :disabled-date="disabledDate" />
                <el-date-picker v-model="returnDate" type="date" placeholder="选择归还日期" :disabled-date="disabledDate" />
            </div>
            <div slot="footer" class="dialog-footer">
                <el-button @click="borrowDialogVisible = false">取消</el-button>
                <el-button type="primary" @click="borrowJournal">确认借阅</el-button>
            </div>
        </el-dialog>

        <el-dialog title="申请委托" v-model="entrustmentDialogVisible" width="30%">
            <div>
                <p>期刊名称: {{ selectedJournal.journal_name }}</p>
                <div><strong>当前馆藏地:</strong> <el-tag>{{ selectedJournal.location_name }}</el-tag></div>
                <el-select v-model="toLocation" placeholder="请选择目标馆藏地" style="width: 100%">
                    <el-option v-for="location in libraryLocations" :key="location.location_id"
                        :label="location.location_name" :value="location.location_id" />
                </el-select>
            </div>
            <div slot="footer" class="dialog-footer">
                <el-button @click="entrustmentDialogVisible = false">取消</el-button>
                <el-button type="primary" @click="confirmEntrustment">确认委托</el-button>
            </div>
        </el-dialog>
    </div>
</template>

<script setup>
import { ref, onMounted } from 'vue';
import { journalApi, libraryLocationApi, entrustmentApi, borrowApi } from '@/request/apiService';
import { ElMessage } from 'element-plus';

const search = ref('');
const locationFilter = ref('全部');
const journals = ref([]);
const libraryLocations = ref([]);
const borrowDialogVisible = ref(false);
const entrustmentDialogVisible = ref(false);
const selectedJournal = ref({});
const borrowDate = ref('');
const returnDate = ref('');
const toLocation = ref(null);

const currentPage = ref(1);
const pageSize = ref(10);
const totalCount = ref(0);

const fetchJournals = async (page = 1) => {
    const filters = { search: search.value, page, pageSize: pageSize.value, location_id: locationFilter.value !== '全部' ? locationFilter.value : undefined };
    const response = await journalApi.getJournalList(filters);
    journals.value = response.data;
    totalCount.value = response.total;
};

const fetchLibraryLocations = async () => {
    const response = await libraryLocationApi.getLibraryLocationList();
    libraryLocations.value = response.data;
};

const searchJournals = async () => {
    currentPage.value = 1;
    await fetchJournals(currentPage.value);
};

const filterByLocation = async (locationId) => {
    locationFilter.value = locationId;
    await fetchJournals(currentPage.value);
};

const borrowJournal = async () => {
    if (!borrowDate.value || !returnDate.value) {
        ElMessage.warning('请填写借阅日期和归还日期！');
        return;
    }
    await borrowApi.addBorrowRecord({ journal_id: selectedJournal.value.journal_id, borrow_date: borrowDate.value, return_date: returnDate.value });
    borrowDialogVisible.value = false;
};

const openBorrowDialog = (journal) => {
    selectedJournal.value = journal;
    borrowDate.value = '';
    returnDate.value = '';
    borrowDialogVisible.value = true;
};

const openEntrustmentDialog = (journal) => {
    selectedJournal.value = journal;
    toLocation.value = null;
    entrustmentDialogVisible.value = true;
};

const confirmEntrustment = async () => {
    if (!toLocation.value || selectedJournal.value.location_id === toLocation.value) {
        ElMessage.warning('请选择有效的目标馆藏地！');
        return;
    }
    await entrustmentApi.addEntrustment({ journal_id: selectedJournal.value.journal_id, from_location_id: selectedJournal.value.location_id, to_location_id: toLocation.value });
    entrustmentDialogVisible.value = false;
};

const disabledDate = (date) => date < new Date().setHours(0, 0, 0, 0);

onMounted(async () => {
    await fetchLibraryLocations();
    await fetchJournals();
});
</script>

<style scoped>
.student-home {
    padding: 20px;
    background-color: #f0f2f5;
    min-height: 100vh;
}

.header-bar {
    display: flex;
    align-items: center;
    justify-content: center;
    padding: 20px;
    background: linear-gradient(90deg, #3498db, #8e44ad);
    border-radius: 12px;
    box-shadow: 0 4px 12px rgba(0, 0, 0, 0.1);
    margin-bottom: 30px;
}

.search-input {
    flex-grow: 1;
    max-width: 600px;
    margin-right: 15px;
    border-radius: 25px;
    padding-left: 15px;
    box-shadow: inset 0 2px 4px rgba(0, 0, 0, 0.1);
}

.search-input .el-input__inner {
    border-radius: 25px;
    padding: 10px 20px;
    background-color: #fff;
    transition: border-color 0.3s, box-shadow 0.3s;
}

.search-input .el-input__inner:focus {
    border-color: #2ecc71;
    box-shadow: 0 0 5px rgba(46, 204, 113, 0.5);
}

.search-button {
    height: 44px;
    border-radius: 25px;
    padding: 0 25px;
    background-color: #2ecc71;
    border-color: #27ae60;
    transition: background-color 0.3s, border-color 0.3s;
}

.search-button:hover {
    background-color: #27ae60;
    border-color: #1e8449;
}

.header-bar .el-icon-search {
    color: #aaa;
}

@media (max-width: 768px) {
    .header-bar {
        flex-direction: column;
    }

    .search-input {
        width: 100%;
        margin-right: 0;
        margin-bottom: 15px;
    }

    .search-button {
        width: 100%;
    }
}

.main-content {
    display: flex;
    gap: 20px;
    margin-top: 20px;
}

.sidebar {
    width: 250px;
    padding: 20px;
    background: white;
    border-radius: 8px;
    box-shadow: 0 4px 8px rgba(0, 0, 0, 0.1);
}

.sidebar-menu {
    display: flex;
    flex-direction: column;
    gap: 10px;
}

.menu-item {
    width: 100%;
    max-width: 240px;
    display: flex;
    align-items: center;
    justify-content: center;
    background-color: #f5f5f5;
    border: none;
    padding: 10px;
    border-radius: 8px;
    cursor: pointer;
    font-size: 16px;
    color: #333;
    transition: background-color 0.3s, color 0.3s;
    text-align: center;
    box-sizing: border-box;
}

.menu-item.active {
    background-color: #3498db;
    color: white;
}

.menu-item:hover {
    background-color: #3498db;
    color: white;
}

.results-section {
    flex: 1;
    padding: 20px;
    background-color: white;
    border-radius: 8px;
    box-shadow: 0 4px 12px rgba(0, 0, 0, 0.1);
}

.journal-list {
    display: flex;
    flex-direction: column;
    gap: 20px;
}

.journal-item {
    display: flex;
    gap: 20px;
    padding: 15px;
    border: 1px solid #ddd;
    border-radius: 8px;
    background-color: #fff;
    transition: box-shadow 0.3s ease, transform 0.2s ease;
    align-items: flex-start;
}

.journal-item:hover {
    box-shadow: 0 6px 15px rgba(0, 0, 0, 0.2);
    transform: translateY(-3px);
}

.journal-cover {
    width: 150px;
    height: 200px;
    object-fit: cover;
    border-radius: 6px;
    background-color: #f5f5f5;
}

.journal-content {
    display: flex;
    flex-direction: row;
    justify-content: space-between;
    width: 100%;
}

.journal-info {
    flex: 3;
    display: flex;
    flex-wrap: wrap;
    gap: 10px;
}

.journal-info p {
    font-size: 14px;
    color: #555;
    margin: 0;
    width: calc(50% - 10px);
}

.journal-title {
    font-size: 18px;
    font-weight: bold;
    color: #333;
    width: 100%;
    margin-bottom: 10px;
}

.journal-actions {
    flex: 1;
    display: flex;
    flex-direction: column;
    gap: 10px;
    align-items: flex-end;
    justify-content: center;
}

.journal-actions .el-button {
    width: 100px;
    text-align: center;
}

.in-stock {
    color: #27ae60;
    font-weight: bold;
}

.out-of-stock {
    color: #e74c3c;
    font-weight: bold;
}

::v-deep .el-button+.el-button {
    margin: 0;
}

.pagination {
    margin-top: 20px;
}
</style>
